package com.mrd.frame.onlinepay.query.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.mrd.frame.domain.AccessConfig;
import com.mrd.frame.domain.Order;
import com.mrd.frame.domain.OrderInteraction;
import com.mrd.frame.domain.TradeStatement;
import com.mrd.frame.domain.params.PayParams;
import com.mrd.frame.onlinepay.query.IPayQuery;
import com.mrd.frame.service.OrderInteractionService;
import com.mrd.frame.service.OrderService;
import com.mrd.frame.service.TradeStatementService;
import com.mrd.weixinpay.util.ChangeUtil;
import com.mrd.weixinpay.util.HttpUtil;
import com.mrd.weixinpay.util.PayCommonUtil;
import com.mrd.weixinpay.util.XMLUtil;

@Component("wxQuery")
public class WxQuery implements IPayQuery {
	private static final Logger logger = Logger.getLogger(WxQuery.class);
	@Autowired
	OrderInteractionService orderInteractionService;
	@Autowired
	OrderService orderService;
	@Autowired
	TradeStatementService	    tradeStatementService;
	@Value("${pay.weixin.orderQuery}")
	private String	            orderQuery;
	/**
	 * 微信支付查询
	 */
	public Map queryOrder(PayParams payParams, AccessConfig accessConfig,
			Order order) throws Exception {
		Map<Object, Object> restMap = new HashMap<Object, Object>();
		String retRsult = "";
		String reMsg = "";
		String reOrder = "";
		OrderInteraction orderInt = new OrderInteraction();
		orderInt.setCreateTime(new Date());
		orderInt.setOrderId(order.getOrderId());// 使用订单id
		orderInt.setOrderInteractionId(String.valueOf(System
				.currentTimeMillis()));
		orderInt.setType("D1");

		String appid = accessConfig.getAppId(); // appid
		String mch_id = accessConfig.getMchId(); // 商业号
		String key = accessConfig.getPrivateKey(); // key
		String currTime = PayCommonUtil.getCurrTime();
		String strTime = currTime.substring(8, currTime.length());
		String strRandom = PayCommonUtil.buildRandom(4) + "";
		String nonce_str = strTime + strRandom;
		String out_trade_no = order.getOrderId();// 发送给微信方用于支付请求的订单号

		SortedMap<Object, Object> params = new TreeMap<Object, Object>();
		params.put("appid", appid);
		params.put("mch_id", mch_id);
		params.put("nonce_str", nonce_str);
		params.put("out_trade_no", out_trade_no);
		String sign = PayCommonUtil.createSign("UTF-8", params, key);
		params.put("sign", sign);

		String requestXML = PayCommonUtil.getRequestXml(params);
		logger.info("向微信发起查询 请求的参数:" + requestXML);
		// 将查询请求存入交互记录表中
		orderInt.setParameters(requestXML);
		orderInt.setType("D1");
		orderInt.setStatus("0");
		int d1 = orderInteractionService.insert(orderInt);
		String resXml = "";
		try {
			// PayConfig.orderQuery
			resXml = HttpUtil.postData(orderQuery, requestXML);
			logger.info("微信返回的查询参数：" + resXml);
			System.out.println(resXml);
			// 将查询请求返回信息存入记录表中
			orderInt.setType("D2");
			orderInt.setStatus("0");
			int d2 = orderInteractionService.insert(orderInt);

			Map map = XMLUtil.doXMLParse(resXml);
			String return_code = (String) map.get("result_code");
			String trade_state = (String) map.get("trade_state");
			String result_code = (String) map.get("result_code");
			String trade_state_desc = (String) map.get("trade_state_desc");
			String transaction_id = (String) map.get("transaction_id ");// 微信支付订单号
			String total_fee = (String) map.get("total_fee");// 订单金额
			if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code)) {
				// trade_state: SUCCESS—支付成功 ，REFUND—转入退款
				// ,NOTPAY—未支付（用户一直没有支付，或者超过时间没有支付）
				// ,CLOSED—已关闭 ,
				// REVOKED—已撤销（刷卡支付） ，USERPAYING--用户支付中（调起密码框后没有输入密码）
				// ，PAYERROR--支付失败(其他原因，如银行返回失败）

				if ("SUCCESS".equals(trade_state)
						|| "REFUND".equals(trade_state)) {
					// 支付已完成，修改支付系统的订单号为支付完成状态
					order.setThirdOrderId(transaction_id);
					order.setStatus("2");

					// 产生实际金额交易的时候存入资金流水表

					TradeStatement tradeStatement = new TradeStatement();
					tradeStatement.setOrderId(order.getOrderId());
					List<TradeStatement> trade = new ArrayList<>();
					trade = tradeStatementService.selectSelective(tradeStatement);
					if(!(trade.size() > 0)) {
						tradeStatement.setOrderId(order.getOrderId());
						tradeStatement.setPayChannel("1");
						tradeStatement.setThirdOrderId(transaction_id);
						tradeStatement.setTotalAmount(Integer.parseInt(total_fee));
						tradeStatement.setTradeNo(order.getTradeNo());
						tradeStatement.setTradeTime(new Date());
						// tradeStatement.setRelatedTradeNo("");
						tradeStatement.setTradeType("1");
						tradeStatement.setTradingStatementsId(String.valueOf(System
						        .currentTimeMillis()));
						tradeStatement.setUserKey(order.getUserKey());
						tradeStatementService.insert(tradeStatement);

					}

				} else if ("CLOSED".equals(trade_state)
						|| "REVOKED".equals(trade_state)
						|| "PAYERROR".equals(trade_state)) {
					// 订单状态 0：处理失败
					order.setStatus("0");
				} else if ("NOTPAY".equals(trade_state)) {
					// 判断时间差，下单超过两小时就将订单状态改为超时
					Date staTime = order.getTimeStart();
					long timeInterval = ChangeUtil.getTimeInterval(new Date(),
							staTime);
					if (timeInterval >= (2 * 60)) {
						order.setStatus("3");
					}
				}
				int r1 = orderService.updateByPrimaryKeySelective(order);
				retRsult = "SUCCESS";
				if(!"".equals(trade_state_desc) && trade_state_desc != null) {
					reMsg = trade_state_desc;
				} else {
					reMsg = "支付成功！";
				}

			} else {
				String errCode = (String) map.get("err_code");
				if ("ORDERNOTEXIST".equals(errCode)) {
					reMsg = "此交易订单号不存在 ";
				} else {
					reMsg = "系统异常请再次调用重新查询";
				}
				retRsult = "FILE";
			}
			restMap.put("retRsult", retRsult);
			restMap.put("reMsg", reMsg);
			restMap.put("reOrder", order);
			// 吊起查询接口，确认订单状态

		} catch (Exception e) {
			orderInt.setType("D2");
			orderInt.setStatus("1");
			int d2 = orderInteractionService.insert(orderInt);
			retRsult = "FILE";

		}

		return restMap;
	}

}
